package com.ysm.smfu.activity;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Looper;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.umeng.analytics.MobclickAgent;
import com.ysm.smfu.R;
import com.ysm.smfu.bean.User;
import com.ysm.smfu.contans.SpKey;
import com.ysm.smfu.protocal.BaseProtocal;
import com.ysm.smfu.protocal.MyStringCallBack;
import com.ysm.smfu.utils.JsonUtil;
import com.ysm.smfu.utils.StoreInfo;
import com.ysm.smfu.utils.PrintUtil;
import com.ysm.smfu.utils.ThreadUtils;
import com.ysm.smfu.utils.ToastUtils;
import com.ysm.smfu.utils.UIUtils;
import com.ysm.smfu.view.XEditText;
import com.ysm.smfu.welcome.SharedConfig;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import chatuidemo.Constant;
import chatuidemo.DemoHelper;
import chatuidemo.db.DBManager;
import easeui.utils.EaseCommonUtils;

/**
 * Created by Administrator on 2016/9/20.
 * 全局的登录页面
 */
public class All_LoginActivity extends BaseActivity {

    @BindView(R.id.et_activity_login_phonenumber)
    XEditText etActivityLoginPhonenumber;
    @BindView(R.id.et_activity_login_password)
    EditText etActivityLoginPassword;
    @BindView(R.id.btn_activity_login_forgetpassword)
    TextView btnActivityLoginForgetpassword;
    @BindView(R.id.btn_activity_login_login)
    Button btnActivityLoginLogin;

    //    @BindView(R.id.logo)
//    ImageView logo;
    private String phoneNumber;
    private SharedPreferences sp;
    private ProgressDialog progressDialog;
    private SharedPreferences currSP;
    private String numPhone;
    private User userInfo;
    private String psd;
    private android.app.AlertDialog.Builder conflictBuilder;
    private String isModifyPsd;
    private String isWec;
    private SharedConfig sharedConfig;
    private SharedConfig privateSharedConfig;

    @Override
    protected void init() {
        super.init();
    }

    @Override
    protected void initViews() {
        super.initViews();
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        //设置分隔属性
        etActivityLoginPhonenumber.setPhone();
        getIntentData();
        if (getIntent().getBooleanExtra(Constant.ACCOUNT_CONFLICT, false) && !isConflictDialogShow) {
            showConflictDialog();
        }
    }

    public boolean isConflict = false;
    private boolean isConflictDialogShow;

    private void showConflictDialog() {
        isConflictDialogShow = true;
        DemoHelper.getInstance().logout(false, null);
        String name = new SharedConfig(UIUtils.getContext()).getCommoneSp().getString(SpKey.NAME, "");
        final SharedPreferences currShared = new SharedConfig(UIUtils.getContext(), name).getPrivateSp();
        String st = getResources().getString(R.string.Logoff_notification);
        if (!All_LoginActivity.this.isFinishing()) {
            // clear up global variables
            try {
                if (conflictBuilder == null)
                    conflictBuilder = new android.app.AlertDialog.Builder(All_LoginActivity.this);
                conflictBuilder.setTitle(st);
                conflictBuilder.setMessage(R.string.connect_conflict);
                conflictBuilder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(final DialogInterface dialog, int which) {
                        StoreInfo.getInstance().clearInfo(sp, currShared);
                        dialog.dismiss();
                        conflictBuilder = null;
//                        finish();
                    }
                });
                conflictBuilder.setCancelable(false);

                android.app.AlertDialog dialog = conflictBuilder.create();
                dialog.setCanceledOnTouchOutside(false);
                dialog.show();
                isConflict = true;
            } catch (Exception e) {
            }
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putBoolean("isConflict", isConflict);
        super.onSaveInstanceState(outState);
    }

    /**
     * 获取Intent传递过来的数据
     */
    private void getIntentData() {
        isModifyPsd = getIntent().getStringExtra("isModifyPsd");
        isWec = getIntent().getStringExtra("isWec");
//        注册页面的手机号
        sharedConfig = new SharedConfig(UIUtils.getContext());
        sp = sharedConfig.getCommoneSp();
        phoneNumber = sharedConfig.getCommoneStringInfo(SpKey.NAME);
        String num = "";
        if (!TextUtils.isEmpty(phoneNumber)) {
            char[] chars = phoneNumber.toCharArray();
            for (int i = 0; i < chars.length; i++) {
                if (i == 3 || i == 7) {
                    num = num + " " + chars[i];
                    continue;
                }
                num = num + chars[i];
            }
            etActivityLoginPhonenumber.setText(num);
            etActivityLoginPassword.requestFocus();
        }
    }

    @Override
    protected void initListener() {
        super.initListener();
    }

    @OnClick({R.id.btn_activity_login_forgetpassword, R.id.btn_activity_login_login, R.id.register})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_activity_login_forgetpassword:
                Intent intent = new Intent(All_LoginActivity.this, My_XiuGai_Activity.class);
                intent.putExtra("position", 5);
                intent.putExtra("loginPsd", "loginPsd");
                startActivity(intent);
                // 设置Activity的切换效果
                overridePendingTransition(R.anim.in_from_right,
                        R.anim.out_to_left);
                break;
            case R.id.btn_activity_login_login:
                String num = etActivityLoginPhonenumber.getText().toString().trim();
                numPhone = num.replace(" ", "");

                psd = etActivityLoginPassword.getText().toString().trim();
                if (psd.length() < 6 || !psd.matches(SpKey.MIMAREGEX)) {
                    showErrordialog("密码必须包含至少一个字母，不得少于六位");
                    break;
                }

                //        如果无网络连接
                if (!EaseCommonUtils.isNetWorkConnected(this)) {
                    Toast.makeText(this, R.string.network_isnot_available, Toast.LENGTH_SHORT).show();
                    return;
                }
                //显示进度条
                showDialg();
//                登录
                login(numPhone, psd);
                break;
            case R.id.register:
                UIUtils.startActivity(Registe_checkActivity.class);
                overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);
                break;
            case R.id.back:
                modifyAfterClear();
                finish();
                overridePendingTransition(0, R.anim.out_to_bottom);
                break;
        }
    }

    private void modifyAfterClear() {
        if (TextUtils.equals(isModifyPsd, "true") || TextUtils.equals(isWec, "isWec")) {
            if (currSP == null) {
                privateSharedConfig = new SharedConfig(UIUtils.getContext(), numPhone);
                currSP = privateSharedConfig.getPrivateSp();
            }
            StoreInfo.getInstance().clearInfo(sp, currSP);
        }
    }

    /**
     * 显示错误对话框
     */
    private void showErrordialog(String msg) {
        AlertDialog dialog = new AlertDialog.Builder(this).setMessage(msg)
                .setNegativeButton("确定", null)
                .create();
        dialog.show();
    }

    /**
     * 登录：同时登陆环信和后台
     *
     * @param numPhone
     * @param psd
     */
    private void login(final String numPhone, final String psd) {
        BaseProtocal.builder(false).login(new MyStringCallBack() {
            @Override
            public void onSuccess(String response) {
                PrintUtil.printRespones("登录信息", response);
                String state = JsonUtil.getState(response);
                if (!TextUtils.equals(state, "1")) {
                    showErrordialog(JsonUtil.getMessage(response));
                    cancleDialog();
                    return;
                }
                // 友盟统计用户Id
                MobclickAgent.onProfileSignIn(numPhone);
                //将用户名和密码保存到本地，以便自动登陆
                userInfo = JsonUtil.getUserInfo(response);
                if (TextUtils.isEmpty(userInfo.user.hxId) || TextUtils.isEmpty(userInfo.user.pwd)) {
                    ToastUtils.showToast("未获取到聊天所需信息");
                    return;
                }
                loginHx(userInfo.user.hxId, userInfo.user.pwd);
            }

            @Override
            public void onFail(Exception e) {
                cancleDialog();
                PrintUtil.printRespones("登录异常", e.getMessage());
                ToastUtils.showToast("网络繁忙，请稍后重试");
            }
        }, numPhone, psd, false);
    }

    /**
     * 环信登录
     *
     * @param psd
     */
    private void loginHx(final String hxId, final String psd) {
        DBManager.getInstance().closeDB();
//        用户昵称为环信ID
        DemoHelper.getInstance().setCurrentUserName(hxId);

//        已经登陆过，本不需再登陆，但有可能用户清除了缓存，但是环信仍然登陆着，需要先退出
        if (EMClient.getInstance().isLoggedInBefore()) {
            EMClient.getInstance().logout(false, new EMCallBack() {
                @Override
                public void onSuccess() {

                    loginToHx(hxId, psd);
                }

                @Override
                public void onError(int i, String s) {
                }

                @Override
                public void onProgress(int i, String s) {
                }
            });
            return;
        }
        loginToHx(hxId, psd);
    }

    /**
     * 登录到环信
     *
     * @param hxId
     * @param psd
     */
    private void loginToHx(String hxId, String psd) {
        PrintUtil.printRespones("登录环信" + hxId + "==" + psd);
        //环信登录
        EMClient.getInstance().login(hxId, psd, new EMCallBack() {
            @Override
            public void onSuccess() {
                PrintUtil.printRespones("环信登录成功");
                saveInfoAndTo();
            }

            @Override
            public void onProgress(int progress, String status) {
            }

            @Override
            public void onError(final int code, final String message) {
                cancleDialog();
                Looper.prepare();
                ThreadUtils.runOnUiThread(new Runnable() {
                    //                    @Override
                    public void run() {
                        showErrordialog(message);
                    }
                });
                Looper.loop();
            }
        });
    }

    /**
     * 保存信息并且跳转
     */
    private void saveInfoAndTo() {
        // 将用户信息保存到数据库
        DBManager.getInstance().saveContact2(userInfo.user);
        sendBroadcastForLoadData();
        EMClient.getInstance().chatManager().loadAllConversations();
        sharedConfig.saveCommoneStringInfo(SpKey.NAME, numPhone);
        privateSharedConfig=new SharedConfig(UIUtils.getContext(), numPhone);
        currSP = privateSharedConfig.getPrivateSp();
        privateSharedConfig.savePrivateInfo(SpKey.PWD, userInfo.user.pwd);
        BaseProtocal.setNull();
        //  将用户信息保存到本地xml文件中
        StoreInfo.getInstance().store(currSP, userInfo);
        // 取消进度条
        cancleDialog();
        finish();

        overridePendingTransition(0, R.anim.out_to_bottom);
    }

    /**
     * 登录完成，发送广播，通知页面加载数据
     */
    private void sendBroadcastForLoadData() {
        Intent intent = new Intent();
        intent.setAction("loginedGoLoadData");
        sendBroadcast(intent);
    }

    /**
     * 显示进度对话框
     */
    private void showDialg() {
        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("正在登录中...");
        if (!progressDialog.isShowing())
            progressDialog.show();
    }

    private void cancleDialog() {
        if (progressDialog != null && progressDialog.isShowing())
            progressDialog.dismiss();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        overridePendingTransition(0, R.anim.out_to_bottom);
        modifyAfterClear();
    }
}
